<template>
  <div class="bg-white/60 backdrop-blur-sm rounded-xl border border-purple-100/20 shadow-lg overflow-hidden">
    <!-- Loading State -->
    <div v-if="loading" class="flex justify-center items-center py-12">
      <div class="flex items-center gap-3">
        <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-indigo-600"></div>
        <span class="text-gray-600">加载中...</span>
      </div>
    </div>

    <div v-else class="overflow-x-auto">
      <table class="min-w-full divide-y divide-gray-200">
        <thead class="bg-gray-50/50">
          <tr>
            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-1/3">
              标题
            </th>
            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-2/5">
              校对进度
            </th>
            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-1/6">
              锁定状态
            </th>
            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-1/6">
              操作
            </th>
          </tr>
        </thead>
        <tbody class="bg-white/40 divide-y divide-gray-200">
          <tr v-if="documents.length === 0">
            <td colspan="4" class="px-6 py-12 text-center text-gray-500">
              <div class="flex flex-col items-center gap-3">
                <DocumentIcon className="w-12 h-12 text-gray-400" />
                <p>暂无文档</p>
              </div>
            </td>
          </tr>
          <tr v-for="doc in documents" :key="doc.id" class="hover:bg-gray-50/50 transition-colors">
            <td class="px-6 py-4 whitespace-nowrap">
              <div class="text-sm font-medium text-gray-900">{{ doc.title }}</div>
            </td>
            <td class="px-6 py-4">
              <div class="flex flex-col gap-2 relative group">
                <div class="flex items-center gap-3">
                  <!-- 分段进度条背景 -->
                  <div class="flex h-3 rounded-full overflow-hidden w-full bg-gray-200 relative">
                    <!-- 分段标记线 -->
                    <div class="absolute inset-0 flex w-full">
                      <div class="w-1/3 h-full border-r border-white/50"></div>
                      <div class="w-1/3 h-full border-r border-white/50"></div>
                      <div class="w-1/3 h-full"></div>
                    </div>
                    
                    <!-- 第一阶段 -->
                    <div 
                      class="h-full bg-blue-500 transition-all duration-300"
                      :class="{ 'opacity-30': doc.step === 0 }"
                      :style="{ width: getStepProgress(doc, 1) }"
                    ></div>
                    <!-- 第二阶段 -->
                    <div 
                      class="h-full bg-purple-500 transition-all duration-300"
                      :class="{ 'opacity-30': doc.step < 2 }"
                      :style="{ width: getStepProgress(doc, 2) }"
                    ></div>
                    <!-- 第三阶段 -->
                    <div 
                      class="h-full bg-green-500 transition-all duration-300"
                      :class="{ 'opacity-30': doc.step < 3 }"
                      :style="{ width: getStepProgress(doc, 3) }"
                    ></div>
                  </div>
                  
                  <!-- 进度描述 -->
                  <span 
                    class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap"
                    :class="{
                      'bg-gray-100 text-gray-800': doc.step === 0,
                      'bg-blue-100 text-blue-800': doc.step === 1,
                      'bg-purple-100 text-purple-800': doc.step === 2,
                      'bg-green-100 text-green-800': doc.step === 3
                    }"
                  >
                    {{ getStepText(doc.step) }}
                  </span>
                </div>
              </div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
              <span v-if="doc.is_lock" class="inline-flex items-center text-red-600 gap-1">
                <LockIcon className="w-4 h-4" />
                <span class="text-sm">{{ doc.locked_user_name }}</span>
              </span>
              <span v-else class="text-sm text-green-600">未锁定</span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm">
              <div class="flex items-center gap-2">
                <div class="relative group">
                  <button
                    @click="isLockByOthers(doc) ? null : handleConfirmCheck(doc)"
                    :disabled="isLockByOthers(doc)"
                    class="inline-flex items-center px-3 py-1 rounded-md text-sm font-medium transition-colors duration-200"
                    :class="[
                      isLockByOthers(doc)
                        ? 'bg-gray-100 text-gray-400 cursor-not-allowed'
                        : 'bg-indigo-100 text-indigo-700 hover:bg-indigo-200'
                    ]"
                  >
                    {{ doc.is_lock && doc.locked_user_name === authStore.user?.username ? '继续校对' : '校对' }}
                  </button>
                  <!-- 悬停提示 -->
                  <div class="absolute bottom-full left-1/2 transform -translate-x-1/2 -translate-y-1 
                              bg-gray-800 text-white text-xs rounded px-2 py-1 mb-1 opacity-0 
                              group-hover:opacity-100 transition-opacity duration-200 pointer-events-none
                              whitespace-nowrap z-50 min-w-[120px] text-center">
                    {{ getButtonTooltip(doc) }}
                    <div class="absolute top-full left-1/2 transform -translate-x-1/2 
                                border-t-4 border-gray-800 border-l-4 border-r-4 border-l-transparent 
                                border-r-transparent h-0 w-0"></div>
                  </div>
                </div>
                <div class="relative group">
                  <button
                    @click="handleView(doc)"
                    class="inline-flex items-center px-3 py-1 rounded-md bg-purple-50 text-purple-700 hover:bg-purple-100 text-sm font-medium transition-colors duration-200"
                  >
                    查看
                  </button>
                  <!-- 查看按钮悬停提示 -->
                  <div class="absolute bottom-full left-1/2 transform -translate-x-1/2 -translate-y-1 
                              bg-gray-800 text-white text-xs rounded px-2 py-1 mb-1 opacity-0 
                              group-hover:opacity-100 transition-opacity duration-200 pointer-events-none
                              whitespace-nowrap z-50 text-center">
                    查看文档详情(不进行校对)
                    <div class="absolute top-full left-1/2 transform -translate-x-1/2 
                                border-t-4 border-gray-800 border-l-4 border-r-4 border-l-transparent 
                                border-r-transparent h-0 w-0"></div>
                  </div>
                </div>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 确认对话框 -->
    <AlertDialog v-model:open="isConfirmDialogOpen">
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>确认校对</AlertDialogTitle>
          <AlertDialogDescription>
            您确定要开始校对《{{ selectedDocument?.title }}》吗？
            {{ selectedDocument?.is_lock && selectedDocument?.locked_user_name === authStore.user?.username 
              ? '该文档已被您锁定，将继续您未完成的校对工作。' 
              : '开始校对后，该文档将被锁定，其他用户将无法同时校对此文档。' }}
          </AlertDialogDescription>
        </AlertDialogHeader> 继续校对 
        <AlertDialogFooter>
          <AlertDialogCancel @click="isConfirmDialogOpen = false">取消</AlertDialogCancel>
          <AlertDialogAction @click="confirmCheck">确定</AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>

    <!-- 提示对话框 -->
    <AlertDialog v-model:open="isTipDialogOpen">
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>提示</AlertDialogTitle>
          <AlertDialogDescription>
            您有正在进行的任务，请先完成当前任务后再开始新的校对。
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogAction @click="isTipDialogOpen = false">我知道了</AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useAuthStore } from '../../../stores/auth'
import { useRouter } from 'vue-router'
import { lockDocument } from '../../../api/document'
import LockIcon from '../../../components/icons/LockIcon.vue'
import DocumentIcon from '../../../components/icons/DocumentIcon.vue'
import { 
  AlertDialog,
  AlertDialogContent,
  AlertDialogHeader, 
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogAction,
  AlertDialogCancel
} from '../../../components/ui/alert-dialog'

const props = defineProps({
  documents: {
    type: Array,
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  },
  inProgressDocuments: {
    type: Array,
    required: true
  }
})

const emits = defineEmits(['check', 'view'])

const authStore = useAuthStore()
const router = useRouter()
const isConfirmDialogOpen = ref(false)
const selectedDocument = ref(null)
const isTipDialogOpen = ref(false)

// 判断文档是否被其他用户锁定
const isLockByOthers = (doc) => {
  return doc.is_lock && doc.locked_user_name !== authStore.user?.username
}

// 获取按钮提示文本
const getButtonTooltip = (doc) => {
  if (isLockByOthers(doc)) {
    return `该文档已被锁定校对中`
  } else if (doc.is_lock && doc.locked_user_name === authStore.user?.username) {
    return '继续您未完成的校对工作'
  } else {
    return '点击开始校对该文档'
  }
}

// 获取步骤文本
const getStepText = (step) => {
  const steps = {
    0: '未开始',
    1: '第一次校对',
    2: '第二次校对',
    3: '第三次校对'
  }
  return steps[step] || '未知状态'
}

// 计算每个阶段的进度宽度
const getStepProgress = (doc, step) => {
  // 如果文档还未开始(step=0)，则所有段显示为0%
  if (doc.step === 0) {
    return '0%'
  }
  
  // 每个阶段占总进度条的1/3
  const stageWidth = 33.33
  
  // 如果当前文档步骤小于传入的step，则此段为0%
  if (doc.step < step) {
    return '0%'
  }
  
  // 如果当前步骤等于传入的step，则根据当前进度计算
  if (doc.step === step) {
    const basePercent = (step - 1) * stageWidth
    const currentPercent = doc.process - basePercent
    const segmentWidth = Math.min(currentPercent, stageWidth)
    return `${segmentWidth}%`
  }
  
  // 如果当前步骤大于传入的step，则此段已完成
  return `${stageWidth}%`
}

// 打开确认对话框
const handleConfirmCheck = (doc) => {
  // 检查用户是否有进行中的任务
  const hasInProgressTask = props.inProgressDocuments.some(d => d.id !== doc.id)

  if (hasInProgressTask) {
    isTipDialogOpen.value = true
    return
  }

  selectedDocument.value = doc
  isConfirmDialogOpen.value = true
}

// 确认校对操作
const confirmCheck = async () => {
  if (selectedDocument.value) {
    try {
      // 调用锁定文档API
      await lockDocument(selectedDocument.value.id)
      // 跳转到校对页面
      router.push(`/document/proofread/${selectedDocument.value.id}`)
    } catch (error) {
      console.error('锁定文档失败:', error)
      // 这里可以添加错误提示
    }
    isConfirmDialogOpen.value = false
    selectedDocument.value = null
  }
}

const handleView = (doc) => {
  emits('view', doc)
}
</script> 